package com.ledi.guns.modular.ledipay.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ledi.guns.common.exception.AppCheckException;
import com.ledi.guns.common.persistence.dao.BillClassMapMapper;
import com.ledi.guns.common.persistence.dao.ClassInfoMapper;
import com.ledi.guns.common.persistence.dao.GradeMapper;
import com.ledi.guns.common.persistence.dao.SchoolInfoMapper;
import com.ledi.guns.common.persistence.dao.UserMapper;
import com.ledi.guns.common.persistence.model.ClassInfo;
import com.ledi.guns.common.persistence.model.Grade;
import com.ledi.guns.common.persistence.model.SchoolInfo;
import com.ledi.guns.common.persistence.model.User;
import com.ledi.guns.common.persistence.model.vo.ClassInfoVo;
import com.ledi.guns.common.util.KeyValue;
import com.ledi.guns.core.shiro.ShiroKit;
import com.ledi.guns.core.shiro.ShiroUser;
import com.ledi.guns.core.util.SystemConstans;
import com.ledi.guns.modular.ledipay.controller.req.clazz.ClassAdd;
import com.ledi.guns.modular.ledipay.controller.req.clazz.ClassinfoReq;
import com.ledi.guns.modular.ledipay.controller.req.clazz.GradeClass;
import com.ledi.guns.modular.ledipay.service.ClassInfoService;

/**
 * 文件名称： com.ledi.guns.modular.ledipay.service.impl.ClassInfoServiceImpl.java<br/>
 * 初始作者： 钟小平<br/>
 * 创建日期： 2018年8月2日<br/>
 * 功能说明： 这里用一句话描述这个类的作用--此句话需删除 <br/>
 * =================================================<br/>
 * 修改记录：<br/>
 * 修改作者 日期 修改内容<br/>
 * ================================================<br/>
 * Copyright (乐迪教育科技有限公司-幼儿事业部) 2017-2018.All rights reserved.<br/>
 */
@Service
public class ClassInfoServiceImpl implements ClassInfoService {

	@Resource
	private ClassInfoMapper classInfoMapper;

	@Resource
	private GradeMapper gradeMapper;

	@Resource
	private UserMapper userMapper;
	@Resource
	private BillClassMapMapper billClassMapMapper;

	@Resource
	private SchoolInfoMapper schoolInfoMapper;

	/**
	 * 方法描述: [班级列表.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年8月2日-下午1:15:22<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	public Page<ClassInfoVo> pageList(Page<ClassInfoVo> page, ClassinfoReq req) {

		if (req.getSchoolId() != null) {

			List<ClassInfoVo> list = classInfoMapper.pageList(page, req.getSearch());

			page.setRecords(list);
			return page;
		}
		ShiroUser currentUser = ShiroKit.getUser();
		User oneUser = userMapper.selectById(currentUser.getId());
		if (!oneUser.getStatus().equals(SystemConstans.YES)) {
			throw new AppCheckException("school.user.notActive.code", "school.user.notActive.message");
		}
		Long schoolId = oneUser.getSchoolId();
		if (schoolId == null) {
			throw new AppCheckException("school.user.noSchool.code", "school.user.noSchool.message");
		}
		req.setSchoolId(schoolId);
		if (!ShiroKit.isDirector()) {
			req.setMasterFlag(SystemConstans.NO);
			req.setUserId(Long.parseLong(oneUser.getId() + ""));
		}

		List<ClassInfoVo> list = classInfoMapper.pageList(page, req.getSearch());

		page.setRecords(list);
		return page;
	}

	/**
	 * 方法描述: [批量新增班级.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年8月2日-下午3:23:52<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	@Transactional
	public void addClassInfoBatch(GradeClass cradeClass) {

		ShiroUser currentUser = ShiroKit.getUser();
		User oneUser = userMapper.selectById(currentUser.getId());
		if (!oneUser.getStatus().equals(SystemConstans.YES)) {
			throw new AppCheckException("school.user.notActive.code", "school.user.notActive.message");
		}
		Long schoolId = oneUser.getSchoolId();
		if (schoolId == null) {
			throw new AppCheckException("school.user.noSchool.code", "school.user.noSchool.message");
		}

		Grade grade = new Grade();
		grade.setName(cradeClass.getGradeName());
		Grade selectOne = gradeMapper.selectOne(grade);

		if (selectOne == null) {

			List<String> classNames = cradeClass.getClassNames();
			List<ClassInfo> listClazz = new ArrayList<ClassInfo>();
			for (String className : classNames) {
				ClassInfo clazz = new ClassInfo();
				clazz.setName(className);
				ClassInfo clazzInfo = classInfoMapper.selectOne(clazz);
				if (clazzInfo == null) {
					clazz.setCreateTime(new Date());
					clazz.setCreatorId(Long.parseLong(currentUser.getId() + ""));
					clazz.setIsDelete(0);
					clazz.setVersionNo(0);
					clazz.setSchoolId(schoolId);
				} else {
					listClazz.add(clazzInfo);
				}
				listClazz.add(clazz);
			}
			grade.setIsDelete(0);
			gradeMapper.insert(grade);
		}

	}

	/**
	 * 方法描述: [修改班级信息.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年8月2日-下午3:36:13<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	@Transactional
	public void changeClassInfo(ClassAdd classAdd) {

		ShiroUser currentUser = ShiroKit.getUser();
		User oneUser = userMapper.selectById(currentUser.getId());
		if (!oneUser.getStatus().equals(SystemConstans.YES)) {
			throw new AppCheckException("school.user.notActive.code", "school.user.notActive.message");
		}
		Long schoolId = oneUser.getSchoolId();
		if (schoolId == null) {
			throw new AppCheckException("school.user.noSchool.code", "school.user.noSchool.message");
		}
		ClassInfo entity = new ClassInfo();
		BeanUtils.copyProperties(classAdd, entity);
		entity.setSchoolId(schoolId);
		if (classAdd.getId() != null) {
			ClassInfo oldClass = classInfoMapper.selectById(classAdd.getId());
			if (classAdd.getFlag() != null && classAdd.getFlag() == 1) {
				entity.setIsDelete(SystemConstans.YES);
			} else {
				List<ClassInfo> selectList = classInfoMapper.selectList(new EntityWrapper<ClassInfo>()
						.eq("is_delete", 0)
						.eq("school_id", schoolId)
						.eq("order_num", classAdd.getOrderNum())
						.eq("grade_id", classAdd.getGradeId()));
				if (CollectionUtils.isNotEmpty(selectList) && !classAdd.getOrderNum().equals(oldClass.getOrderNum())) {
					throw new AppCheckException("school.classs.exit.code", "school.classs.exit.message");
				}
			}
			entity.setUpdaterId(Long.parseLong(oneUser.getId() + ""));
			entity.setUpdateTime(new Date());
			entity.setUpdaterRole(oneUser.getRoleid());
			classInfoMapper.updateById(entity);

		} else {
			List<ClassInfo> selectList = classInfoMapper.selectList(new EntityWrapper<ClassInfo>()
					.eq("is_delete", 0)
					.eq("school_id", schoolId)
					.eq("order_num", classAdd.getOrderNum())
					.eq("grade_id", classAdd.getGradeId()));
			if (CollectionUtils.isNotEmpty(selectList)) {
				throw new AppCheckException("school.classs.exit.code", "school.classs.exit.message");
			}
			entity.setCreatorId(Long.parseLong(oneUser.getId() + ""));
			entity.setCreateTime(new Date());
			entity.setIsDelete(SystemConstans.NO);
			entity.setCreatorRole(oneUser.getRoleid());
			classInfoMapper.insert(entity);
		}

	}

	/**
	 * 方法描述: [年级或者班级列表.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年8月3日-上午11:02:17<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	public List<KeyValue> gradeOrClassList(Long gradeId, int flag) {

		ShiroUser currentUser = ShiroKit.getUser();
		User oneUser = userMapper.selectById(currentUser.getId());
		if (!oneUser.getStatus().equals(SystemConstans.YES)) {
			throw new AppCheckException("school.user.notActive.code", "school.user.notActive.message");
		}
		Long schoolId = oneUser.getSchoolId();
		if (schoolId == null) {
			throw new AppCheckException("school.user.noSchool.code", "school.user.noSchool.message");
		}

		if (gradeId == null) {
			SchoolInfo schoolInfo = schoolInfoMapper.selectById(schoolId);
			Integer schoolType = schoolInfo.getSchoolType();
			List<Grade> selectList = null;
			if (schoolType < 10) {
				selectList = gradeMapper.selectList(
						new EntityWrapper<Grade>().eq("is_delete", 0).eq("school_type", schoolType + ""));
			} else {
				String type1 = (schoolType + "").substring(0, 1);
				String type2 = (schoolType + "").substring(1);
				selectList = gradeMapper.selectList(
						new EntityWrapper<Grade>().eq("is_delete", 0).eq("school_type", type1));
				List<Grade> selectList1 = gradeMapper.selectList(
						new EntityWrapper<Grade>().eq("is_delete", 0).eq("school_type", type2));
				selectList.addAll(selectList1);
			}
			if (flag == 1) {

				List<KeyValue> list = new ArrayList<KeyValue>();
				if (CollectionUtils.isNotEmpty(selectList)) {
					for (Grade x : selectList) {
						KeyValue kv = new KeyValue();
						kv.setKey(Integer.parseInt(x.getId() + ""));
						kv.setLeaf(SystemConstans.YES);
						kv.setValue(x.getName());
						Map<String, Object> classmap = new HashMap<String, Object>();
						classmap.put("school_id", schoolId);
						classmap.put("grade_id", x.getId());
						classmap.put("is_delete", SystemConstans.NO);
						List<ClassInfo> classlist = null;
						if (ShiroKit.isDirector()) {
							classlist = classInfoMapper.selectByMap(classmap);
						} else {
							classlist = classInfoMapper.selectByTeacherId(Long.parseLong(oneUser.getId() + ""), schoolId, x.getId());
						}
						if (CollectionUtils.isNotEmpty(classlist)) {
							List<ClassInfo> collect = classlist.stream().sorted((p1, p2) -> p1.getOrderNum().compareTo(p2.getOrderNum())).collect(Collectors.toList());

							List<KeyValue> listclass = new ArrayList<KeyValue>();
							for (ClassInfo y : collect) {
								KeyValue kv1 = new KeyValue();
								kv1.setKey(Integer.parseInt(y.getId() + ""));
								String name = StringUtils.isNotBlank(y.getName()) ? " (" + y.getName() + ")" : "";
								kv1.setValue(y.getOrderNum() + "班" + name);
								listclass.add(kv1);
							}
							kv.setChildren(listclass);
						}
						list.add(kv);
					}
				}
				return list;
			} else {

				List<KeyValue> list = new ArrayList<KeyValue>();
				if (CollectionUtils.isNotEmpty(selectList)) {
					selectList.forEach(x -> {
						KeyValue kv = new KeyValue();
						kv.setKey(Integer.parseInt(x.getId() + ""));
						kv.setValue(x.getName());
						list.add(kv);
					});
				}
				return list;
			}
		} else {
			Map<String, Object> columnMap = new HashMap<String, Object>();
			columnMap.put("school_id", schoolId);
			columnMap.put("grade_id", gradeId);
			columnMap.put("is_delete", SystemConstans.NO);
			List<ClassInfo> selectList = classInfoMapper.selectByMap(columnMap);
			List<KeyValue> list = new ArrayList<KeyValue>();
			if (CollectionUtils.isNotEmpty(selectList)) {
				selectList.forEach(x -> {
					KeyValue kv = new KeyValue();
					kv.setKey(Integer.parseInt(x.getId() + ""));
					kv.setValue(x.getName());
					list.add(kv);
				});
			}
			return list;
		}

	}

	/**
	 * 方法描述: [账单对应班级列表.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年8月22日-下午4:28:06<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	public List<ClassInfoVo> getClassByBillId(Long billId) {

		List<ClassInfoVo> selectList = billClassMapMapper.selectByBillId(billId);
		return selectList;
	}

	/**
	 * 方法描述: [学校所有班级.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年8月23日-下午2:39:50<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	public List<ClassInfo> findAll(Long schoolId) {

		List<ClassInfo> selectList = classInfoMapper.selectList(new EntityWrapper<ClassInfo>()
				.eq("is_delete", 0)
				.eq("school_id", schoolId)
				);
		return selectList;
	}
}
